import {
  ds
} from "../../../../tools/data"
import {
  users
} from "../../../../tools/users"
import {
  pages
} from '../../../../tools/pages'
import {
  roles
} from "../../../../tools/roles";
import {
  ui
} from '../../../../tools/ui'
import {
  shops
} from '../../../../tools/shops'
import {
  checkTool
} from '../../../../tools/check'
import {
  shopList
} from "~/static/shop";

const cloudPrefix = getApp().globalData.cloudPrefix

Page({
  data: {
    action: 'read',
    id: '',
    item: {
      role: 'custom'
    },
    errMsg: "",
    roles: roles.names,
    shopList: shops.getShopList(),
    cloudPrefix,
    addr: {},
    shopName: {}
  },
  async init() {
    const {
      id, // user id
    } = this.data
    const that = this

    ds.coll('users').where({
      _id: id
    }).get({
      success: function (res) {
        if (res.data && res.data.length > 0) {
          that.setData({
            item: res.data[0]
          })
        }
        that.initShopName()
        that.loadAddr(res.data[0])
      }
    });
  },
  initShopName() {
    const {
      item
    } = this.data
    // let shopName = ''
    // item.shops.forEach(id => {
    //   shopName = `${shopName}, ${shops.getShop(id).name}`
    // })
    const shopName = {}
    shopList.forEach(shop => {
      shopName[`${shop.id}`] = shop.name
    })
    this.setData({
      shopName
    })
  },
  loadAddr(user) {
    ds.coll('delivery_addr')
      .where({
        _openid: user._openid
      })
      .get()
      .then(res => {
        const addr = res?.data[0]
        this.setData({
          addr
        })
      })
  },
  selImg() {
    wx.navigateTo({
      url: '../imgSelect/index'
    })
  },
  addImgClick() {
    this.selImg()
  },
  imgClick() {
    this.selImg()
  },
  imgSelected(files) {
    const that = this
    if (files.length > 0) {
      that.data.item.thumb = files[0]

      that.setData({
        item: that.data.item
      })
    }
  },
  save() {
    checkTool.check(this.getFields())
    ui.loading()
    ds.cloudUpdate('users', this.data.id, this.data.item, res => {
      pages.back(prevPage => {
        ui.loading(false)
        prevPage.init && prevPage.init()
      });
    })
  },
  getFields() {
    const item = this.data.item
    return [{
      value: item.phoneNumber,
      regex: "( +)|(\\d{11})",
      title: '手机号',
      allowEmpty: true
    }, {
      value: item.role,
      title: '角色'
    }, {
      value: item.shop,
      title: '所在门店',
      fn: v => {
        if (item.role == 'admin' || item.role == 'custom') return true
        return v?.name
      }
    }]
  },
  onDel() {
    ui.confirmx('确定删除吗？').then(res => {
      if (!res) return
      ds.cloudRemove('users', {
        id: this.data.id
      }, res => {
        pages.back(prePage => {
          prePage.init && prePage.init()
        })
      })
    })
  },
  // 配送费结算
  onDeliveryFeeTap(e) {
    // console.log(this.data.item)
    const staff = this.data.item
    const staffId = staff._id,
      nickName = staff.personInfo.nickName
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/deliFee?staffId=${staffId}&nickName=${nickName}`,
    })
  },
  // 提成结算
  onDeductFeeTap(e) {
    const staff = this.data.item
    const staffId = staff._id,
      nickName = staff.personInfo?.nickName || '（无昵称）'
    wx.navigateTo({
      url: `/pages/usercenter/staff/deductFee/deductFee?staffId=${staffId}&nickName=${nickName}`,
    })
  },
  onDealRefoundTap() {
    const staff = this.data.item
    wx.navigateTo({
      url: '/pages/usercenter/pladge/pladge?action=manage&staffId=' + staff._id,
    })
  },
  onValueChange(e) {
    if (this.data.action != 'edit') return
    const {
      name
    } = e.target.dataset
    const that = this
    if (name == 'tags') {
      this.data.item[e.target.dataset.name] = e.detail.value.replaceAll(' ', '').split(/[,，]/);
    } else if (name == 'vip') {
      this.data.item[name] = (e.detail.value ? '1' : '0')
    } else {
      this.data.item[e.target.dataset.name] = e.detail.value
    }
    this.setData({
      item: that.data.item
    })
  },
  focusRole(e) {
    wx.navigateTo({
      url: `/pages/usercenter/staff/role/index?id=${this.data.id}`,
    })
  },
  // onShopTap(e) {
  //   const shopList = this.data.shopList
  //   const item = this.data.item
  //   // console.log(this.data.item, this.data.shopList)
  //   const items = {}
  //   shopList.forEach(ele => {
  //     items[ele.id] = ele.name
  //   })
  //   // console.log(items)
  //   ui.actionSheet(items, (value, key) => {
  //     item.shop = shops.getShop(key)
  //     this.setData({
  //       item
  //     })
  //   })
  // },
  onMobileTap(e) {
    const mobile = e.currentTarget.dataset.mobile
    if (!mobile) return
    ui.makePhoneCall(mobile)
  },
  onLoad(option) { // { action: 'new'|'edit'|'read', id } 
    this.setData({
      ...option
    })

    this.init();
  },
});